package com.ruoyi.questionnaire.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ruoyi.questionnaire.domain.Questionnaire;
import com.ruoyi.questionnaire.domain.QuestionnaireAnswer;
import com.ruoyi.questionnaire.domain.QuestionnaireOption;
import com.ruoyi.questionnaire.domain.QuestionnaireQuestion;
import com.ruoyi.questionnaire.mapper.QuestionnaireAnswerDetailMapper;
import com.ruoyi.questionnaire.mapper.QuestionnaireAnswerMapper;
import com.ruoyi.questionnaire.mapper.QuestionnaireMapper;
import com.ruoyi.questionnaire.mapper.QuestionnaireOptionMapper;
import com.ruoyi.questionnaire.mapper.QuestionnaireQuestionMapper;
import com.ruoyi.questionnaire.service.IQuestionnaireService;

@Service
public class QuestionnaireServiceImpl implements IQuestionnaireService {
    // 注入问卷Mapper
    @Autowired
    private QuestionnaireMapper questionnaireMapper;
    // 注入问卷题目Mapper
    @Autowired
    private QuestionnaireQuestionMapper questionMapper;
    // 注入问卷答卷Mapper
    @Autowired
    private QuestionnaireAnswerMapper answerMapper;
    // 注入问卷答卷详情Mapper
    @Autowired
    private QuestionnaireAnswerDetailMapper answerDetailMapper;
    @Autowired
    private QuestionnaireOptionMapper optionMapper;
    // 注入问卷答卷详情Mapper
    @Override
    public Questionnaire selectQuestionnaireById(Long id) {
        return questionnaireMapper.selectQuestionnaireById(id);
    }
    // 查询问卷
    @Override
    public List<Questionnaire> selectQuestionnaireList(Questionnaire questionnaire) {
        // 直接返回Questionnaire对象列表，因为Mapper已经配置了resultMap
        return questionnaireMapper.selectQuestionnaireList(questionnaire);
    }
    // 新增问卷
    @Override
    public int insertQuestionnaire(Questionnaire questionnaire) {
        questionnaire.setCreateTime(new Date());
        questionnaire.setUpdateTime(new Date());
        return questionnaireMapper.insertQuestionnaire(questionnaire);
    }
    // 更新问卷
    @Override
    public int updateQuestionnaire(Questionnaire questionnaire) {
        questionnaire.setUpdateTime(new Date());
        return questionnaireMapper.updateQuestionnaire(questionnaire);
    }
    // 删除问卷
    @Override
    public int deleteQuestionnaireByIds(Long[] ids) {
        return questionnaireMapper.deleteQuestionnaireByIds(ids);
    }
    // 删除问卷
    @Override
    public int deleteQuestionnaireById(Long id) {
        return questionnaireMapper.deleteQuestionnaireById(id);
    }
    // 发布问卷
    @Override
    public int publishQuestionnaire(Long id) {
        Questionnaire q = questionnaireMapper.selectQuestionnaireById(id);
        if (q == null || "published".equals(q.getStatus())) return 0;
        q.setStatus("published");
        q.setUpdateTime(new Date());
        return questionnaireMapper.updateQuestionnaire(q);
    }
    // 关闭问卷
    @Override
    public int closeQuestionnaire(Long id) {
        Questionnaire q = questionnaireMapper.selectQuestionnaireById(id);
        if (q == null || "closed".equals(q.getStatus())) return 0;
        q.setStatus("closed");
        q.setUpdateTime(new Date());
        return questionnaireMapper.updateQuestionnaire(q);
    }
    // 获取问卷统计信息
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getQuestionnaireStats(Long id) {
        Map<String, Object> stats = new HashMap<>();
        // 1. 题目数量
        int questionCount = questionMapper.countByQuestionnaireId(id);
        // 2. 答卷数量
        int answerCount = answerMapper.countByQuestionnaireId(id);
        // 3. 查询所有题目
        List<QuestionnaireQuestion> questions = questionMapper.selectQuestionnaireQuestionList(id);
        // 4. 查询所有答卷
        List<QuestionnaireAnswer> answers = answerMapper.selectQuestionnaireAnswerList(new QuestionnaireAnswer() {{ setQuestionnaireId(id); }});
        // 5. 统计平均用时（假设只有submitTime，无法统计用时，返回空或0）
        double avgTime = 0;
        // 6. 统计完成率（假设完成率=答卷数/1，或100%）
        int completionRate = answerCount > 0 ? 100 : 0;
        // 7. 题目统计
        List<Map<String, Object>> questionStats = new ArrayList<>();
        for (QuestionnaireQuestion q : questions) {
            Map<String, Object> qStat = new HashMap<>();
            qStat.put("id", q.getId());
            qStat.put("content", q.getContent());
            qStat.put("questionType", q.getQuestionType());
            qStat.put("total", answerCount);
            if ("text".equals(q.getQuestionType())) {
                // 文本题，收集所有答案
                List<String> textAnswers = answerDetailMapper.getTextAnswers(q.getId());
                qStat.put("answers", textAnswers);
            } else {
                // 单选/多选题，统计每个选项被选次数
                List<QuestionnaireOption> options = optionMapper.selectQuestionnaireOptionList(q.getId());
                List<Map<String, Object>> optionStats = new ArrayList<>();
                Map<String, Integer> valueCount = new HashMap<>();
                // 统计所有答卷详情
                List<Map<String, Object>> optionCountList = answerDetailMapper.getOptionStats(q.getId());
                for (Map<String, Object> oc : optionCountList) {
                    String v = (String) oc.get("optionValue");
                    Integer c = ((Number) oc.get("count")).intValue();
                    // 多选题optionValue可能为逗号分隔
                    if ("multiple".equals(q.getQuestionType()) && v != null && v.contains(",")) {
                        for (String vv : v.split(",")) {
                            valueCount.put(vv, valueCount.getOrDefault(vv, 0) + c);
                        }
                    } else {
                        valueCount.put(v, valueCount.getOrDefault(v, 0) + c);
                    }
                }
                for (QuestionnaireOption opt : options) {
                    Map<String, Object> optStat = new HashMap<>();
                    optStat.put("id", opt.getId());
                    optStat.put("optionLabel", opt.getOptionLabel());
                    optStat.put("count", valueCount.getOrDefault(opt.getOptionValue(), 0));
                    optionStats.add(optStat);
                }
                qStat.put("options", optionStats);
            }
            questionStats.add(qStat);
        }
        // 8. 趋势数据
        List<Map<String, Object>> trendRaw = answerDetailMapper.getSubmissionTrend(id);
        List<String> dates = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        for (Map<String, Object> t : trendRaw) {
            dates.add(String.valueOf(t.get("date")));
            counts.add(((Number)t.get("count")).intValue());
        }
        Map<String, Object> trendData = new HashMap<>();
        trendData.put("dates", dates);
        trendData.put("counts", counts);
        // 9. 返回
        stats.put("totalSubmissions", answerCount);
        stats.put("totalQuestions", questionCount);
        stats.put("completionRate", completionRate);
        stats.put("avgTime", avgTime);
        stats.put("questions", questionStats);
        stats.put("trendData", trendData);
        return stats;
    }

    @Override
    public int countByCreateBy(String createBy) {
        return questionnaireMapper.countByCreateBy(createBy);
    }
} 